define(['jquery', 'bootstrap', 'backend', 'table', 'form','vue'], function ($, undefined, Backend, Table, Form,Vue) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'calculation/salary_calculation_template/index' + location.search,
                    add_url: 'calculation/salary_calculation_template/add',
                    edit_url: 'calculation/salary_calculation_template/edit',
                    del_url: 'calculation/salary_calculation_template/del',
                    multi_url: 'calculation/salary_calculation_template/multi',
                    import_url: 'calculation/salary_calculation_template/import',
                    table: 'salary_calculation_template',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                visible: false,
                showToggle: false,
                showColumns: false,
                search:false,
                showExport: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'template_name', title: __('Template_name'), operate: 'LIKE'},
                        // {field: 'staff_type', title: __('Staff_type'),searchList: {"1": '普通教师', "2": '非普通教师'},formatter: Table.api.formatter.status,custom:{ 1:'success',2:'warning'}},
                        {field: 'create_time', title: __('Create_time'), operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate',
                            buttons: [
                                {
                                    name: 'show_salary_benchmark_log',
                                    text: '复制',
                                    icon: '',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: 'calculation/salary_calculation_template/edit?type=1',
                                },
                            ],
                            title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
            table.on('load-success.bs.table',function(data){
                $(".btn-editone").data("area", ["90%","90%"]);
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                var app = new Vue({
                    el: '#app',
                    data: {
                        staffTypes: {1:'普通教师',2:'非普通教师'},
                        templateName:'',
                        copy_type:Config.copy_type,
                        selectedStaffType: 1,
                        formDropdownOptions:[

                        ],
                        itemTypes: {
                            1: '扣除项',
                            2: '累加项',
                            3: '单独显示',
                            4: '不显示',
                        },
                        calculationForms: [

                        ],
                        id:Config.id
                    },

                    methods: {

                        DropdownOptions: function (selectedStaffType){
                            var that = this;
                            $.post('salary/salary_benchmark/get_template', { type: selectedStaffType }, function (data) {
                                that.formDropdownOptions = data.data;
                            }, 'json');
                        },

                        updateDropdownOptions: function(selectedStaffType) {
                            var that = this;
                            that.DropdownOptions(selectedStaffType);
                            this.calculationForms = [];
                        },

                        addNewForm: function () {
                            this.calculationForms.push({
                                itemName: '',
                                itemType: Object.keys(this.itemTypes)[0], // 默认类型为第一个选项的键值
                                showDropdownMenu: false,
                                showCalculatedWay: false,
                                calculatedFormula: '',
                                calculatedFormulaValue: [],
                                customValue: 0.00
                            });
                        },


                        toggleDropdown: function(index, dropdownName) {
                            // 关闭其他下拉框
                            for (let i = 0; i < this.calculationForms.length; i++) {
                                if (i !== index) {
                                    this.calculationForms[i].showDropdownMenu = false;
                                    this.calculationForms[i].showCalculatedWay = false;
                                }
                            }
                            // 切换当前项的下拉菜单状态
                            this.calculationForms[index][dropdownName] = !this.calculationForms[index][dropdownName];
                            if(dropdownName == 'showDropdownMenu'){
                                this.calculationForms[index].showCalculatedWay = false;
                            }else{
                                this.calculationForms[index].showDropdownMenu = false;
                            }
                        },

                        selectDropdownItem: function(itemValue,item, form,event) {
                            event.preventDefault(); // 阻止默认链接点击行为
                            if (form.calculatedFormula !== '') {
                                const lastChar = form.calculatedFormula.charAt(form.calculatedFormula.length - 1);
                                if(lastChar === ')'){
                                    Toastr.error('上一个值不能是右括号'); form.showDropdownMenu = false;return false;
                                }

                                if(!'+-*/('.includes(form.calculatedFormula.charAt(form.calculatedFormula.length - 1))){
                                    Toastr.error('上一个值不能是基准项/自定义数值'); form.showDropdownMenu = false;return false;
                                }

                            }
                            form.calculatedFormula += item;
                            form.calculatedFormulaValue.push({
                                type: '1', value: itemValue,name:item
                            });
                            form.showDropdownMenu = false;
                        },
                        selectCalculatedWayItem: function(item, form,event) {
                            event.preventDefault(); // 阻止默认链接点击行为
                            if(form.calculatedFormula === '' && '+-*/)'.includes(item)){
                                Toastr.error('开头不能是加减乘除右括号');  form.showCalculatedWay = false;return false;
                            }
                            var lastStr = form.calculatedFormula.charAt(form.calculatedFormula.length - 1);
                            if (form.calculatedFormula !== '' && '+-*/'.includes(item)  && '+-*/('.includes(lastStr)) {
                                Toastr.error('前面不能是加减乘除左括号'); form.showCalculatedWay = false;return false;
                            }
                            if(item === ")" && form.calculatedFormula !== ''){
                                if('+-*/('.includes(lastStr)){
                                    Toastr.error('前面不能是加减乘除右括号左括号'); form.showCalculatedWay = false;return false;
                                }
                                var Bracket = this.checkBracket(form.calculatedFormula)
                                if(Bracket.leftParenthesesCount < Bracket.rightParenthesesCount + 1){
                                    Toastr.error('右括号比左括号多'); form.showCalculatedWay = false;return false;
                                }

                            }

                            if(item === "(" && form.calculatedFormula !== '' && !'+-*/('.includes(lastStr)){
                                Toastr.error('上一个值不能是基准项/自定义数值/右括号'); form.showDropdownMenu = false;return false;
                            }
                            form.calculatedFormula += item;
                            form.calculatedFormulaValue.push({
                                type: '2', value: item,name:item
                            });
                            form.showCalculatedWay = false;
                        },

                        confirmCustomValue: function(form,event) {
                            event.preventDefault(); // 阻止默认链接点击行为
                            const lastChar = form.calculatedFormula.charAt(form.calculatedFormula.length - 1);
                            form.showDropdownMenu = false;
                            form.showCalculatedWay = false;
                            if(lastChar === ')'){
                                Toastr.error('上一个值不能是右括号'); return false;
                            }

                            if(!'+-*/('.includes(form.calculatedFormula.charAt(form.calculatedFormula.length - 1))){
                                Toastr.error('上一个值不能是基准项/自定义数值'); return false;
                            }
                            form.calculatedFormula += form.customValue;
                            form.calculatedFormulaValue.push({
                                type: '3', value: form.customValue,name:form.customValue
                            });
                            form.showDropdownMenu = false;
                            form.showCalculatedWay = false;
                            form.customValue = 0.00;
                        },
                        removeForm: function(index) {
                            this.calculationForms.splice(index, 1);
                        },

                        removeLastItem(index) {
                            const form = this.calculationForms[index];
                            if (form.calculatedFormulaValue.length > 0) {
                                // 移除最新添加到 calculatedFormulaValue 中的项
                                form.calculatedFormulaValue.pop();

                                // 重新构建 calculatedFormula 字符串
                                form.calculatedFormula = '';
                                form.calculatedFormulaValue.forEach(item => {
                                    form.calculatedFormula += item.name;
                                });
                            }
                        },

                        submitForm: function() {
                            var hasError = false;
                            if(this.templateName === ''){
                                Toastr.error('模板名称不能为空'); return false;
                            }
                            const formData = {
                                id:this.id,
                                copy_type:this.copy_type,
                                templateName: this.templateName,
                                staffType: this.selectedStaffType,
                                calculationForms: this.calculationForms.map((form, index) => {
                                    if (form.itemName === '') {
                                        Toastr.error(`第${index + 1}个项目名称不能为空`);
                                        hasError = true;
                                        return false;
                                    }
                                    if (form.calculatedFormula === '') {
                                        Toastr.error(`第${index + 1}个计算公式不能为空`);
                                        hasError = true;
                                        return false;
                                    }
                                    var Bracket = this.checkBracket(form.calculatedFormula);
                                    if (Bracket.leftParenthesesCount != Bracket.rightParenthesesCount) {
                                        Toastr.error(`第${index + 1}个右括号左括号数量不一致`);
                                        hasError = true;
                                        return false;
                                    }
                                    if('+-*/('.includes(form.calculatedFormula.charAt(form.calculatedFormula.length - 1))){
                                        Toastr.error(`第${index + 1}个最后不能是加减乘除左括号`); hasError = true; return false;
                                    }
                                    return {
                                        itemName: form.itemName,
                                        itemType: form.itemType,
                                        calculatedFormula: form.calculatedFormula,
                                        calculatedFormulaValue: form.calculatedFormulaValue,
                                    };
                                }).filter(form => form !== false)
                            };
                            if (hasError) {
                                return;
                            }
                            // 提交表单数据到后台
                            $.ajax({
                                type: 'POST',
                                url: 'calculation/salary_calculation_template/add', // 替换成你的后台接口地址
                                data: JSON.stringify(formData),
                                contentType: 'application/json',
                                success: function(data) {
                                    if(data.code == 1){
                                        parent.Toastr.success('添加成功');
                                        parent.$(".btn-refresh").trigger("click");
                                        var index = parent.Layer.getFrameIndex(window.name);
                                        parent.Layer.close(index);
                                    }else{
                                        Toastr.error(data.msg);
                                        return false;
                                    }
                                },
                                error: function(error) {
                                    Toastr.error('网络错误');
                                    return false;
                                }
                            });
                        },
                        checkBracket:function(calculatedFormula){
                            var leftParenthesesCount = 0;
                            var rightParenthesesCount = 0;
                            for (var i = 0; i < calculatedFormula.length; i++) {
                                if (calculatedFormula.charAt(i) === '(') {
                                    leftParenthesesCount++;
                                } else if (calculatedFormula.charAt(i) === ')') {
                                    rightParenthesesCount++;
                                }
                            }
                            return {'leftParenthesesCount':leftParenthesesCount,'rightParenthesesCount':rightParenthesesCount};
                        },

                        loadEditData: function() {
                            var that = this;
                            var recordId = this.id;
                            if (!recordId) {
                                return;
                            }
                            // 发送异步请求获取数据库中的编辑数据
                            $.post('calculation/salary_calculation_template/edit', { id: recordId }, function (data) {
                                if(data.code != 1) {
                                    Toastr.error(data.msg);
                                }
                                var data = data.data;
                                that.templateName = data.template_name;
                                that.selectedStaffType = data.staff_type;
                                that.DropdownOptions(that.selectedStaffType);
                                // 根据编辑数据初始化表单项
                                that.calculationForms = data.calculationForms.map(form => {
                                    return {
                                        itemName: form.itemName,
                                        itemType: form.itemType,
                                        showDropdownMenu: false,
                                        showCalculatedWay: false,
                                        calculatedFormula: form.calculatedFormula,
                                        calculatedFormulaValue: form.calculatedFormulaValue,
                                        customValue: 0.00
                                    };
                                });
                            });
                        },

                    },
                    mounted() {
                        this.DropdownOptions(this.selectedStaffType);
                        this.loadEditData();
                    }
                });


                Form.api.bindevent($("form[role=form]"));
            }


        }
    };
    return Controller;
});
